<template>
  <div class="form-layout form-layout4">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor :itemList="cpItemList" />
    </div>
    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="cpPropRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <template v-if="cpisClosed">
            <div id="box-close" class="box-title">作废信息</div>
            <customFormItem label="作废时间" name="gmtClosed" :parent="_self" :form="form" />
            <customFormItem label="作废人" name="closeUser" :parent="_self" :form="form" />
            <customFormItem label="作废原因" name="closedReason" :parent="_self" :form="form" />
          </template>

          <div id="box-base" class="box-title">订单信息</div>
          <customFormItem label="订单编号" name="code" :parent="_self" :form="form"
                          :type="constCommon.formItemType.staticHtml.name"  :config="{defaultValue: '自动获取'}"/>
          <customFormItem label="医院" name="hospitalId" :parent="_self" :form="form" ref="hospitalId"
                          :type="constCommon.formItemType.selectStatic.name" :config="{options: utilVuex.getHospitalListForOrderAdd()}"
                          @change="hospitalIdChange"
                          :disabled="!propParent.cpFormNew  || hpDisabled"
                          help="保存后不可修改"
          />

          <customFormItem
            label="收货仓库"
            name="warehouseName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="warehouseNameBefore"
            :disabled="!propParent.cpFormNew"
            help="保存后不可修改"
          />

          <customFormItem
            label="供应商"
            name="supplierName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="spSelectBefore"
            :disabled="!propParent.cpFormNew|| spDisabled"
            help="保存后不可修改"
          />
          <customFormItem label="需求科室" name="demandDeptName" :parent="_self" :form="form" v-show="strings.isNotBlank(form.demandDeptName)" disabled/>

          <customFormItem label="要求送达时间" name="gmtRequireLatestDelivery" :parent="_self" :form="form" :type="constCommon.formItemType.datePicker.name" />

          <customFormItem label="寄售" name="isConsignment" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name"
                          :config="{flagValueBoolean: false}"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />
          <customFormItem label="标签管理" name="isOneThingOneYard" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name"
                          :config="{flagValueBoolean: false}"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />
          <customFormItem label="商品类型" name="materialTypeCode" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.baseMatrType}"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />


          <customFormItem label="需求科室" name="demandDeptName" :parent="_self" :form="form" v-show="false"/>
          <customFormItem label="订单金额" name="totalAmount" :parent="_self" :form="form" disabled/>
          <customFormItem label="备注" name="remark" :parent="_self" :form="form" />

          <div id="box-dtl" class="box-title">订单明细</div>
          <data-view
            propViewKey="purchase_order_item_crud"
            :propIsTdesign="true"
            :propParentPage="_self"
            ref="childDataView"
            :propAutoFetchData="false"
            :propTableHide="!form.id"
            propTableHideMsg="保存完主单据再添加采购明细"
            :propOnlyQueryAll="propReadonly"
            :propInitData="form"
            @edit-input="editInput"
            :propBeforeClick="propBeforeClickDtl"
            :propNoEditRow="true"
            @afterTableDataChange="afterTableDataChange"
            :propDisabledRowSaveClearActived="true"
          />
        </template>
      </customForm>
    </div>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import customUpload from '@/components/custom/form/customUpload.vue'
import goodsCategoryDrawer from '@/components/custom/bus/goodsCategoryDrawer.vue'


export default {
  help: '订单-详情',
  data() {
    return {
      form: {},
      viewData: {},
      spDisabled: true,
      hpDisabled: true,
    }
  },
  methods: {
    // 加载明细数据
    fetchChildData() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('poId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(queryWrapper)
    },
    // 当前登录供应商信息
    getCurrentSp() {
      let deptType = this.utils.getCurrentUser().deptType
      if (this.constCommon.deptType.supplier != deptType) {
        this.spDisabled = false
        return
      }
      let spInfo = this.utils.getSpInfo()
      if (spInfo && spInfo.id) {
        this.$set(this.form, 'supplierId', spInfo.id)
        this.$set(this.form, 'supplierName', spInfo.name)
        this.spDisabled = true
      }
    },
    // 当前登录医院信息
    getCurrentHp() {
      let deptType = this.utils.getCurrentUser().deptType
      if (this.constCommon.deptType.hospital != deptType) {
        this.hpDisabled = false
        return
      }
      let hpInfo = this.utils.getHpInfo()
      if (hpInfo && hpInfo.id) {
        this.$set(this.form, 'hospitalId', hpInfo.id)
        this.$set(this.form, 'hospitalName', hpInfo.name)
        this.hpDisabled = true
      }
    },

    // 供应商选择前
    spSelectBefore() {
      if (this.strings.isBlank(this.form.hospitalId)) {
        this.utilMessage.warning('请先选择医院')
        this.$refs.hospitalId.focus()
        return
      }
      console.log('this.form', this.form)
      this.utilSelect.sp(this.spSelect, this.form.hospitalId)
    },

    // 供应商选择
    spSelect(row) {
      this.$set(this.form, 'supplierId', row.id)
      this.$set(this.form, 'supplierName', row.name)
    },

    // 仓库选择前
    warehouseNameBefore() {
      if (this.strings.isBlank(this.form.hospitalId)) {
        this.utilMessage.warning('请先选择医院')
        this.$refs.hospitalId.focus()
        return
      }
      this.utilSelect.hospitalWarehouse(this.warehouseNameSelect, this.form.hospitalId)
    },

    // 仓库选择
    warehouseNameSelect(row) {
      this.$set(this.form, 'warehouseId', row.id)
      this.$set(this.form, 'warehouseName', row.name)
    },

    // 医院选择
    hospitalIdChange(value, item) {
      this.$set(this.form, 'hospitalName', item.name)
      if (!this.spDisabled) {
        this.$set(this.form, 'supplierId', null)
        this.$set(this.form, 'supplierName', null)
      }
      this.$set(this.form, 'warehouseId', null)
      this.$set(this.form, 'warehouseName', null)
    },
    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({row, column}) {
      if (column.property == 'qty') { //订单数量
        this.$set(row, 'subtotalAmount', this.utilNum.toFixed(row.qty * row.price))
      }
    },
    // 列表添加按钮
    propBeforeClickDtl(button, formData , rowData, that) {
      //列表添加按钮 其他入库
      if (button.key == 'vb-add') {
        this.utilSelect.hospitalMaterialMore(this.matrSelect,
          this.form.hospitalId,
          this.form.supplierId,
          this.form.isOneThingOneYard,
          this.form.isConsignment,
          this.form.materialTypeCode,
        )
        return false
      }
      return true;
    },
    // 批量保存明细
    matrSelect(rows, isLoadForm) {
      this.utilVue.loadShow(true)
      rows.forEach(row => {
        row.poId = this.form.id
        row.id = null
        if (row.unit == row.orderUnit) {
          row.orderQty = 1
        }
        row.qty = 1
        row.subtotalAmount = this.utilNum.toFixed(row.qty * row.price)
      })
      this.$ajax.put('/order/purchase_order_items/batch_save', rows).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.fetchChildData()
          this.afterTableDataChange()
        }
      })
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData) => {
        this.form = global.utils.jsonClone(formData)
        this.$set(this.form, 'id', this.form.id)
        if (this.propParent.cpFormNew) {
          this.$set(this.form, 'isOneThingOneYard', 0)
          this.$set(this.form, 'isConsignment', 0)
          this.$set(this.form, 'fromType', 'SCP')
          this.getCurrentSp()
          this.getCurrentHp()
        }
        this.fetchChildData()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data) {
        let {key: buttonKey} = button
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
  },
  components: { customAnchor, customUpload, goodsCategoryDrawer},
  computed: {
    cpPropRules() {
      let rule = this.propRules || {}
      return rule
    },
    cpisClosed() {
      return [true,1].includes(this.form.isClosed)
    },
    cpItemList() {
      let rule = this.propRules || {}
      let itemList = [
        { name: 'box-base', title: '订单信息' },
        { name: 'box-dtl', title: '订单明细' }
      ]
      if (this.cpisClosed){
        itemList.unshift({ name: 'box-close', title: '作废信息' })
      }
      return itemList
    }
  },
}
</script>
